package com.cloudfast.platform;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.cloudfast.common.encode.EncodeUtils;
import com.cloudfast.common.encode.Md5Encode;
import com.cloudfast.platform.dict.entity.Dict;
import com.cloudfast.platform.dict.entity.DictType;
import com.cloudfast.platform.dict.service.DictService;
import com.cloudfast.platform.menu.entity.Menu;
import com.cloudfast.platform.menu.service.MenuService;
import com.cloudfast.platform.oauthclient.OauthClientDetail;
import com.cloudfast.platform.oauthclient.OauthClientDetailDao;
import com.cloudfast.platform.org.entity.Org;
import com.cloudfast.platform.org.service.OrgService;
import com.cloudfast.platform.role.entity.Role;
import com.cloudfast.platform.role.service.RoleService;
import com.cloudfast.platform.user.entity.User;
import com.cloudfast.platform.user.service.UserService;

/**
 * -启动项目的执行步骤
 *
 * @author liuyw
 * @date 2022年8月25日
 */
@Component
public class InitDataBase implements ApplicationRunner {
    protected static final Logger logger = LoggerFactory.getLogger(Logger.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private DictService dictService;
    @Autowired
    private MenuService menuService;

    @Autowired
    private OauthClientDetailDao oauthClientDetailDao;

    /**
     * 初始化字典信息 -
     */
    public void initDict() {

        DictType dictSex = new DictType("sex", "性别");
        dictService.saveDictType(dictSex);
        // 初始化字典
        Dict dict = new Dict(dictSex.getDictCode(), dictSex.getDictName(), "男", "1", 1);
        dictService.save(dict);

        dict = new Dict(dictSex.getDictCode(), dictSex.getDictName(), "女", "0", 0);
        dictService.save(dict);

        DictType dictRankCode = new DictType("rankCode", "用户职能");
        dictService.saveDictType(dictRankCode);
        // 初始化用户职能
        dict = new Dict(dictRankCode.getDictCode(), dictRankCode.getDictName(), "默认", "rankCode", 0);
        dictService.save(dict);

        DictType menuScope = new DictType("permission_scope", "菜单域");
        dictService.saveDictType(menuScope);

        dict = new Dict(menuScope.getDictCode(), menuScope.getDictName(), "门户首页", "Portal", 0);
        dictService.save(dict);
        dict = new Dict(menuScope.getDictCode(), menuScope.getDictName(), "系统管理", "System", 1);
        dictService.save(dict);

        DictType menuType = new DictType("menu_type", "菜单类型");
        dictService.saveDictType(menuType);
        dict = new Dict(menuType.getDictCode(), menuType.getDictName(), "菜单", "1", 0);
        dictService.save(dict);
        dict = new Dict(menuType.getDictCode(), menuType.getDictName(), "按钮", "2", 1);
        dictService.save(dict);
        dict = new Dict(menuType.getDictCode(), menuType.getDictName(), "大屏", "3", 2);
        dictService.save(dict);

        DictType routerType = new DictType("router_type", "路由类型");
        dictService.saveDictType(routerType);
        dict = new Dict(routerType.getDictCode(), routerType.getDictName(), "目录", "dir_route", 0);
        dictService.save(dict);
        dict = new Dict(routerType.getDictCode(), routerType.getDictName(), "主路由", "main_route", 1);
        dictService.save(dict);
        dict = new Dict(routerType.getDictCode(), routerType.getDictName(), "子路由", "sub_route", 2);
        dictService.save(dict);

        DictType appType = new DictType("app_type", "免密登入类型");
        dictService.saveDictType(appType);
        dict = new Dict(appType.getDictCode(), appType.getDictName(), "钉钉", "ding", 0);
        dictService.save(dict);
        dict = new Dict(appType.getDictCode(), appType.getDictName(), "微信", "wechat", 1);
        dictService.save(dict);

        DictType appScope = new DictType("app_scope", "APP范围");
        dictService.saveDictType(appScope);
        dict = new Dict(appScope.getDictCode(), appScope.getDictName(), "企业内", "enterprise", 0);
        dictService.save(dict);
        dict = new Dict(appScope.getDictCode(), appScope.getDictName(), "第三方", "other", 1);
        dictService.save(dict);

        DictType systemGrantType = new DictType("system_grant_type", "登入模式");
        dictService.saveDictType(systemGrantType);
        dict = new Dict(systemGrantType.getDictCode(), systemGrantType.getDictName(), "密码模式", "password", 0);
        dictService.save(dict);
        dict = new Dict(systemGrantType.getDictCode(), systemGrantType.getDictName(), "短信模式", "sms", 1);
        dictService.save(dict);
        dict = new Dict(systemGrantType.getDictCode(), systemGrantType.getDictName(), "刷新模式", "refresh_token", 2);
        dictService.save(dict);
        dict = new Dict(systemGrantType.getDictCode(), systemGrantType.getDictName(), "验证码模式", "capcha", 3);
        dictService.save(dict);
        dict = new Dict(systemGrantType.getDictCode(), systemGrantType.getDictName(), "客户端模式", "client_credentials", 4);
        dictService.save(dict);
        dict = new Dict(systemGrantType.getDictCode(), systemGrantType.getDictName(), "钉钉模式", "ding", 5);
        dictService.save(dict);
        dict = new Dict(systemGrantType.getDictCode(), systemGrantType.getDictName(), "微信模式", "wechat", 6);
        dictService.save(dict);
        DictType orgType = new DictType("org_type", "机构类型");
        dictService.saveDictType(orgType);

        dict = new Dict(orgType.getDictCode(), orgType.getDictName(), "组织", "org", 0);
        dictService.save(dict);
        dict = new Dict(orgType.getDictCode(), orgType.getDictName(), "部门", "dept", 1);
        dictService.save(dict);
        dict = new Dict(orgType.getDictCode(), orgType.getDictName(), "合作伙伴", "third", 1);
        dictService.save(dict);

        DictType screenType = new DictType("screen_type", "大屏类型");
        dictService.saveDictType(screenType);
        dict = new Dict(screenType.getDictCode(), screenType.getDictName(), "内部", "me", 0);
        dictService.save(dict);
        dict = new Dict(screenType.getDictCode(), screenType.getDictName(), "外部", "other", 0);
        dictService.save(dict);

        DictType screenRouterType = new DictType("screen_router_type", "大屏跳转类型");
        dictService.saveDictType(screenRouterType);
        dict = new Dict(screenRouterType.getDictCode(), screenRouterType.getDictName(), "主窗口", "self", 0);
        dictService.save(dict);
        dict = new Dict(screenRouterType.getDictCode(), screenRouterType.getDictName(), "其他窗口", "_blank", 0);
        dictService.save(dict);

        DictType emailType = new DictType("email_host", "邮箱类型");
        dictService.saveDictType(emailType);
        dict = new Dict(emailType.getDictCode(), emailType.getDictName(), "chinaunicom", "hqs.mail.chinaunicom.cn", 0);
        dictService.save(dict);
        dict = new Dict(emailType.getDictCode(), emailType.getDictName(), "qq", "smtp.qq.com", 2);
        dictService.save(dict);
        dict = new Dict(emailType.getDictCode(), emailType.getDictName(), "163", "smtp.163.com", 3);
        dictService.save(dict);
    }

    private String appendCheckCode(String menuPath, String code) {
        StringBuilder checkCode = new StringBuilder(menuPath);
        checkCode.append("/").append(code);
        String c = checkCode.toString().replaceAll("/", ":");
        if (c.startsWith(":")) {
            c = c.substring(1, c.length());
        }
        return c;
    }

    /**
     * -初始化信息
     *
     * @author liuyw
     * @date 2020年4月30日
     */
    public void init() {
        try {
            List<User> list = userService.findList();
            if (list == null || list.isEmpty()) {
                initDict();

                StringBuilder roleMenus = new StringBuilder();
                // 添加菜单
                Menu adminMenu = new Menu(1L, "主目录", -1L, "icon", "1", "", "", 0);
                adminMenu.setIsAdmin("super");
                adminMenu.setRouterType("dir_route");
                menuService.save(adminMenu);
                Menu systemLayoutMenu = new Menu(2L, "门户首页", adminMenu.getId(), "icon", "1", "", "Portal", 0);
                systemLayoutMenu.setIsAdmin("super");
                systemLayoutMenu.setRouterType("dir_route");

                menuService.save(systemLayoutMenu);
                Menu systemLayoutMenu1 = new Menu(3L, "后台管理", adminMenu.getId(), "icon", "1", "", "System", 0);
                systemLayoutMenu1.setIsAdmin("super");
                systemLayoutMenu1.setRouterType("dir_route");

                menuService.save(systemLayoutMenu1);

                Menu sysMenu = new Menu("基础管理", systemLayoutMenu1.getId(), "el-icon-v-caidan", "1", "", "System", 0);
                menuService.save(sysMenu);
                roleMenus.append(sysMenu.getId()).append(",");
                Menu sys_user = new Menu("用户管理", sysMenu.getId(), "el-icon-v-user", "1",
                        "/user-center/user/index", "System", 1, "/user");
                menuService.save(sys_user);
                roleMenus.append(sys_user.getId()).append(",");

                // 添加用户权限
                Menu permission = new Menu("添加用户", appendCheckCode(sys_user.getPath(), "add"), sys_user.getId(),
                        "System", 1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加用户权限
                permission = new Menu("编辑用户", appendCheckCode(sys_user.getPath(), "edit"), sys_user.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加用户权限
                permission = new Menu("删除用户", appendCheckCode(sys_user.getPath(), "delete"), sys_user.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加用户权限
                permission = new Menu("用户授权", appendCheckCode(sys_user.getPath(), "grant"), sys_user.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                Menu sys_org = new Menu("部门管理", sysMenu.getId(), "el-icon-v-org", "1",
                        "/user-center/dept/index", "System", 2, "/dept");
                menuService.save(sys_org);
                roleMenus.append(sys_org.getId()).append(",");

                // 添加机构权限
                permission = new Menu("添加部门", appendCheckCode(sys_org.getPath(), "add"), sys_org.getId(), "System", 1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加用户权限
                permission = new Menu("编辑部门", appendCheckCode(sys_org.getPath(), "edit"), sys_org.getId(), "System", 1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加用户权限
                permission = new Menu("删除部门", appendCheckCode(sys_org.getPath(), "delete"), sys_org.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                Menu sys_role = new Menu("角色管理", sysMenu.getId(), "el-icon-v-role", "1",
                        "/user-center/role/index", "System", 3, "/role");
                menuService.save(sys_role);
                roleMenus.append(sys_role.getId()).append(",");

                // 添加角色权限
                permission = new Menu("添加角色", appendCheckCode(sys_role.getPath(), "add"), sys_role.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加角色权限
                permission = new Menu("编辑角色", appendCheckCode(sys_role.getPath(), "edit"), sys_role.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加角色权限
                permission = new Menu("删除角色", appendCheckCode(sys_role.getPath(), "delete"), sys_role.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                Menu sys_menu = new Menu("菜单管理", sysMenu.getId(), "el-icon-v-menu", "1",
                        "/user-center/menu/index", "System", 4, "/menu");
                menuService.save(sys_menu);
                roleMenus.append(sys_menu.getId()).append(",");

                // 添加角色权限
                permission = new Menu("添加菜单", appendCheckCode(sys_menu.getPath(), "add"), sys_menu.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加角色权限
                permission = new Menu("编辑菜单", appendCheckCode(sys_menu.getPath(), "edit"), sys_menu.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加角色权限
                permission = new Menu("删除菜单", appendCheckCode(sys_menu.getPath(), "delete"), sys_menu.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                Menu sys_dict = new Menu("字典管理", sysMenu.getId(), "el-icon-v-dict", "1",
                        "/user-center/dict/index", "System", 5, "/dict");
                menuService.save(sys_dict);
                roleMenus.append(sys_dict.getId()).append(",");

                // 添加角色权限
                permission = new Menu("添加字典", appendCheckCode(sys_dict.getPath(), "add"), sys_dict.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加角色权限
                permission = new Menu("编辑字典", appendCheckCode(sys_dict.getPath(), "edit"), sys_dict.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                // 添加角色权限
                permission = new Menu("删除字典", appendCheckCode(sys_dict.getPath(), "delete"), sys_dict.getId(), "System",
                        1);
                menuService.save(permission);
                roleMenus.append(permission.getId()).append(",");

                Menu appClient = new Menu("APP管理", sysMenu.getId(), "el-icon-v-text-app", "1",
                        "/user-center/app/index", "System", 6, "/app/client");
                menuService.save(appClient);
                roleMenus.append(appClient.getId()).append(",");

                Menu oauthClient = new Menu("授权管理", sysMenu.getId(), "el-icon-v-client_app", "1",
                        "/user-center/oauth/index", "System", 6, "/oauth/client");
                menuService.save(oauthClient);
                roleMenus.append(oauthClient.getId()).append(",");

                Menu email = new Menu("邮件配置", sysMenu.getId(), "el-icon-v-email", "1",
                        "/user-center/email/conf", "System", 6, "/conf/email");
                menuService.save(email);
                roleMenus.append(email.getId()).append(",");

                // 初始化角色
                Role role = new Role(1L, "系统管理员", "super_admin", "super");
                role.setMenus(roleMenus.toString());
                this.roleService.save(role);

                // 默认角色
                Role defaultRole = new Role(2L, "默认角色", "default_user", "super");
                this.roleService.save(defaultRole);

                // 初始化部门
                Org org = new Org("主部门", "01", -1L);
                org.setIsAdmin("super");
                org.setOrgType("org");
                this.orgService.save(org);

                // 初始化用户
                User adminUser = new User("admin", "管理员", "13000000001", org.getId(), "1", "rankCode", "super", 100000L);
                this.userService.save(adminUser);
                this.roleService.addUser(role.getId(), adminUser.getId());
                // 初始化客户端
                OauthClientDetail oauthClientDetail = new OauthClientDetail();
                oauthClientDetail.setClientId("cloud");
                oauthClientDetail.setClientName("系统默认");
                oauthClientDetail.setAppSecret(Md5Encode.appSecret(oauthClientDetail.getClientId()));
                oauthClientDetail.setClientSecret(EncodeUtils.encode(oauthClientDetail.getAppSecret()));
                oauthClientDetail.setAuthorizedGrantTypes("captcha,refresh_token");
                oauthClientDetail.setScope("cloud");
                oauthClientDetail.setDelFlag("1");
                oauthClientDetailDao.save(oauthClientDetail);
                oauthClientDetail = new OauthClientDetail();
                oauthClientDetail.setClientId("micro");
                oauthClientDetail.setClientName("内部服务");
                oauthClientDetail.setAppSecret(Md5Encode.appSecret(oauthClientDetail.getClientId()));
                oauthClientDetail.setClientSecret(EncodeUtils.encode(oauthClientDetail.getAppSecret()));
                oauthClientDetail.setAuthorizedGrantTypes("client_credentials");
                oauthClientDetail.setScope("micro");
                oauthClientDetail.setDelFlag("1");
                oauthClientDetailDao.save(oauthClientDetail);
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        init();
    }
}
